package com.sample.thread.pool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* @comments
* @author  zg
* @date 2021年3月13日
*/
public class ThreadPoolTester {

    public static void main(String[] args) {
        //实例化一个线程
        PoolThread t = new PoolThread();
        
        // -----------------------------------------------------------
        //ExecutorService executor = Executors.newCachedThreadPool();//创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
        //ExecutorService executor = Executors.newFixedThreadPool(10);//定长线程池，可控制线程最大并发数，超出的线程会在队列中等待
        //ExecutorService executor = Executors.newScheduledThreadPool(10);//定长线程池，支持定时及周期性任务执行。
        ExecutorService executor = Executors.newSingleThreadExecutor();//单线程化的线程池，只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
        
        executor.execute(t);
        
     // -----------------------------------------------------------
        RejectedExecutionHandler rejectHandler = new ThreadPoolExecutor.AbortPolicy();//默认，队列满了丢任务抛出异常
        int corePoolSize = 5; //核心池的大小（即线程池中的线程数目大于这个参数时，提交的任务会被放进任务缓存队列）
        int maximumPoolSize = 10; //线程池最大能容忍的线程数
        long keepAliveTime = 5; //线程存活时间 
        TimeUnit unit = TimeUnit.MINUTES; //keepAliveTime的时间单位
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);//任务缓存队列，用来存放等待执行的任务
        ExecutorService executor1 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, rejectHandler);
        executor1.execute(t);
    }

}
